package com.xx.happychatboot.middleware.rocketmq.utils;

import cn.hutool.core.util.RandomUtil;
import com.xx.happychatboot.middleware.netty.domain.enums.RocketMqTypeEnum;
import com.xx.happychatboot.middleware.rocketmq.annotation.SecureInvoke;
import com.xx.happychatboot.middleware.rocketmq.constants.RocketMqConstants;
import com.xx.happychatboot.middleware.rocketmq.domain.dto.RocketMqCommonDto;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.transaction.annotation.Transactional;

/**
 * RocketMQ 生产者工具类
 */
public class RocketMqProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 发送消息
     * @param topic 消息主题
     * @param body 消息体
     */
    public void sendMsg(String topic, Object body) {
        // 构建消息
        Message<Object> build = MessageBuilder.withPayload(body).build();
        // 发送消息
        rocketMQTemplate.send(topic, build);
    }

    /**
     * 发送可靠消息，在事务提交后保证发送成功
     * @param topic 消息主题
     * @param body 消息体
     * @param key 消息键
     */
    @SecureInvoke
    public void sendSecureMsg(String topic, Object body, Object key) {
        // 构建带有键的消息
        Message<Object> build = MessageBuilder
                .withPayload(body)
                .setHeader("KEYS", key)
                .build();
        // 发送消息
        rocketMQTemplate.send(topic, build);
    }

    /**
     * 构建并发送消息
     * @param Code
     * @param uid
     * @param key
     * @param topic
     */
    public void buildAndSendSecureMsg(Integer Code, Long uid, String key, String topic) {
        RocketMqCommonDto rocketMqCommonDto = new RocketMqCommonDto();
        rocketMqCommonDto.setCode(Code);
        rocketMqCommonDto.setUid(uid);
        // 获取当前代理对象并调用 sendSecureMsg 方法
        RocketMqProducer proxy = applicationContext.getBean(RocketMqProducer.class);
        proxy.sendSecureMsg(topic, rocketMqCommonDto, key);
    }
}